#include <iostream> 
#include <string.h>
#include "flv_parse.h"
#include "librtmp/rtmp_sys.h"

FLV_Parser::FLV_Parser (){

    unused_len = 0;
    unused = (uint8_t *)malloc(128 * 1024);
    header_ok = false;
    std::cout<<"constuct flv parser"<<std::endl;
}
FLV_Parser::~FLV_Parser (){
    std::cout<<"deconstuct flv parser"<<std::endl;
    while (!aq.empty())
    {
        TAG *tag = aq.front();
        delete tag;
        aq.pop();  // Delete the 1st element
    }
    while (!vq.empty())
    {
        TAG *tag = vq.front();
        delete tag;
        vq.pop();  // Delete the 1st element
    }
    while (!sq.empty())
    {
        TAG *tag = sq.front();
        delete tag;
        sq.pop();  // Delete the 1st element
    }
}

int FLV_Parser::consume(char *data, int total){
    if ((data == nullptr) || total <= 0){
        return -1;
    }
    if (!header_ok) {
        if (total >= FLV_HEADER_LEN) { 
            if((data[0] == 'F') && (data[1] == 'L') && (data[2] == 'V')) {
               header_ok = true;
            }
        }

        total -= FLV_HEADER_LEN;
        data += FLV_HEADER_LEN;
    }
    uint8_t type;
    uint32_t timestamp;
    uint32_t data_size;
    uint8_t *tag_data;
    uint32_t pre_tag_size;
    char * pp;

    memcpy(unused + unused_len, data, total);
    unused_len += total;

    if (unused_len >= TAG_LEN )
    {
        type  = (unused[0] & 0x1F);
        pp = (char*)&data_size;
        pp[3] = 0;
        pp[2] = unused[1];
        pp[1] = unused[2];
        pp[0] = unused[3];

        pp = (char*)&timestamp;
        pp[2] = unused[4];
        pp[1] = unused[5];
        pp[0] = unused[6];
        pp[3] = unused[7];
    }else return 0;
    uint32_t tmp = data_size + TAG_LEN + PRE_TAG_LEN;
    if (unused_len < tmp)
     return 0;

    tag_data = (uint8_t *)malloc(data_size);
    memcpy(tag_data, unused + TAG_LEN, data_size);
  
    pp = (char *)&pre_tag_size;  
    pp[3] =  unused[TAG_LEN + data_size];
    pp[2] =  unused[TAG_LEN + data_size + 1];
    pp[1] =  unused[TAG_LEN + data_size + 2];
    pp[0] =  unused[TAG_LEN + data_size + 3];
   
    unused_len -= tmp;
    if (unused_len > 0) {
        memmove(unused, unused + tmp, unused_len);
    }
    TAG *tag = new TAG();
    tag->type = type;
    tag->tag_data = tag_data;
    tag->data_size = data_size;
    tag->timestamp = timestamp;
    tag->streamid = 0x0000;
    if (type == RTMP_PACKET_TYPE_VIDEO)
        vq.push(tag);
    else if (type == RTMP_PACKET_TYPE_AUDIO)
        aq.push(tag);
    else 
        sq.push(tag);
    return 0;    
}

//int main(){
 //   FLV_Parser a ; char *p = "FLV000000";
  //  a.consume(p, 5);
//}

